/**
 * 
 */
package com.cnhaimei.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.cnhaimei.vod.FavoriteManager;
import com.cnhaimei.vod.MyActivityManager;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.logic.EventsManager;
import com.cnhaimei.vod.logic.HomeActivity;
import com.cnhaimei.vod.logic.EventsManager.EventsListener;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.net.XVod;

/**
 * @author Jin001.Wu@gmail.com <br>
 * @date 2011-7-1
 *
 */
public abstract class BaseActivity extends Activity implements OnClickListener, EventsListener{
	protected boolean observtDisconnect = true;
	protected boolean mIsWaiting = false;
	protected View mWaitView = null;
	protected AlertDialog mMyToastDialog = null;
	
	private final int MSG_CLOSE_MYTOAST = 100;
	protected Activity mSelfActivity;
	protected WakeLock mWakeLock = null;
	private String TAG = "BaseActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		onCreate(savedInstanceState, true);
		mSelfActivity = this;
		
		MyActivityManager.G().push(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		MyActivityManager.G().pop();
	}
	
	protected void onCreate(Bundle savedInstanceState, boolean obserDisconnected) {
		setTitleStyle();
		//TODO:HD版本要改为横屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		super.onCreate(savedInstanceState);
		this.observtDisconnect = obserDisconnected;
		if (this.observtDisconnect) {
			XVod.G().registerListener(EventsManager.Event.DISCONNECT, this);
		}
	}
	
	private void setTitleStyle() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub		
		super.onResume();
		PowerManager pManager = ((PowerManager) getSystemService(POWER_SERVICE));  
		mWakeLock = pManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK  
		               | PowerManager.ON_AFTER_RELEASE, this.getClass().getName());  
		if (mWakeLock != null) {
			mWakeLock.acquire();
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (isFinishing() && observtDisconnect) {
			XVod.G().unRegisterListener(EventsManager.Event.DISCONNECT, this);
		}

		if(null != mWakeLock){  
		    mWakeLock.release();  
		}  
		

		try {
			if (FavoriteManager.G().isDataChanged()) {
				FavoriteManager.G().save();
			}
			FavoriteManager.G().setDataChanged(false);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, e.getMessage());
		}
	}
	
	public void onEvent(int event, Object obj, boolean isSuc) {
		switch (event) {
		case EventsManager.Event.DISCONNECT: {
			if (obj != null && obj instanceof Integer) {
				int id = (Integer) obj;
				if (id == NetManager.G().getDCManangerId()) {
					finish();
				}
			}
		}
			break;
		default:
			break;
		}
	}
	
	protected void startActivity(String action) {
		Intent i = new Intent(action);
		startActivity(i);
	}
	
	protected void startActivity(String action, int requestCode) {
		Intent i = new Intent(action);
		startActivityForResult(i, requestCode);
	}
	
	protected void setClickable(int... ids) {
		for (int i = 0; i < ids.length; i++) {
			View v = findViewById(ids[i]);
			if (v != null)
				v.setOnClickListener(this);
		}
	}

	protected void setFocusable(int... ids) {
		for (int i = 0; i < ids.length; i++) {
			View v = findViewById(ids[i]);
			if (v != null)
				v.setFocusable(true);
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
//	public void onAttachedToWindow() {
//		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
//		super.onAttachedToWindow();
//
//	}
	
	protected final void showWaiting(boolean isBlur, String strWaitTip) {
		mIsWaiting = true;
	    try {
	        WindowManager.LayoutParams lp = null;
	        if (isBlur) {
	            lp = new WindowManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_BLUR_BEHIND | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, PixelFormat.TRANSLUCENT);
	        }
	        else {
	            lp = new WindowManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, PixelFormat.TRANSLUCENT);
	        }
	         
	        WindowManager mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
	        if (mWaitView == null) {
	            LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            mWaitView = inflate.inflate(R.layout.v8_waiting_layout, null);
	        }
	        if (strWaitTip.length() > 0)
	        {
	        	TextView tip = (TextView)mWaitView.findViewById(R.id.waiting_tip);
	        	tip.setText(strWaitTip);
	        }
	         
	        mWindowManager.addView(mWaitView, lp);
	    }
	    catch (Throwable e) {
	        mIsWaiting = false;
	        Log.e(this.getClass().getName(), "[showWaiting]");
	    }
	}
	     
	protected final void hideWaiting() {
		mIsWaiting = false;
	    try {
	        if (mWaitView != null) {
	            WindowManager mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
	            mWindowManager.removeView(mWaitView);
	            mWaitView = null;
	        }
	    }
	    catch (Throwable e) {
	        Log.e(this.getClass().getName(), "[showWaiting]", e);
	    }
	}

	//定义Handler对象
	private Handler mMyToastHandler = new Handler(){
	   @Override
	   //当有消息发送出来的时候就执行Handler的这个方法
	   public void handleMessage(Message msg){
	      super.handleMessage(msg);
	      //只要执行到这里就关闭对话框
	      mMyToastDialog.dismiss();
	   }
	};
	//显示3秒钟的提示语
	protected final void showMyToast(String strTip)
	{
		mMyToastDialog = new AlertDialog.Builder(this).create();
		mMyToastDialog.setMessage(strTip);
		mMyToastDialog.show();

		//mMyToastHandler.removeMessages(MSG_CLOSE_MYTOAST);
		mMyToastHandler.sendEmptyMessageDelayed(MSG_CLOSE_MYTOAST, 1500);
	}
	

	public float scale(float x) {
		DisplayMetrics dm = this.getResources().getDisplayMetrics();
		
        return (int) (x * dm.density);
	}
}
